package com.burt.web.controllers;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.burt.web.service.TestService;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import javax.websocket.Session;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

/**
 * Created by Burt
 * on 27/4/17.
 * Description:
 */
@Controller
public class TestController {
    private static final Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private WebApplicationContext context;

    @Autowired
    private RedisTemplate<String, Session> redisTemplate;

    @Autowired
    private TestService testService;

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;

    @RequestMapping("/zrange")
    @ResponseBody
    public String zrange(String key, Integer start, Integer end) {
        return JSON.toJSONString(redisTemplate.opsForZSet().range(key, start, end));
    }

    @RequestMapping("/show")
    @ResponseBody
    public String show(String uri, Integer period) {
        String hash = String.format("%s:%s", period, uri);
        JSONObject result = new JSONObject();
        Map<Object, Object> dataMap = redisTemplate.opsForHash().entries("count:" + hash);
        for (Map.Entry entry : dataMap.entrySet()) {
            logger.info("key={},count={}", DateFormatUtils.format(new Date(Long.parseLong((String) entry.getKey()) * 1000), "yyyy-MM-dd'T'HH:mm:ss"), entry.getValue());
            result.put(DateFormatUtils.format(new Date(Long.parseLong((String) entry.getKey()) * 1000), "yyyy-MM-dd HH:mm:ss"), entry.getValue());
        }
        return result.toJSONString();
    }
/*
    @RequestMapping("/get")
    @ResponseBody
    public String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }*/

    @RequestMapping("/hgetall")
    @ResponseBody
    public String hgetAll(String key) {
        return JSON.toJSONString(redisTemplate.opsForHash().entries(key));
    }

   /* @RequestMapping("/set")
    @ResponseBody
    public String set(String key, String val) {
        redisTemplate.opsForValue().set(key, val);
        return redisTemplate.opsForValue().get("test");
    }*/

    @RequestMapping("/test")
    public String hello() {
        System.out.println(testService.toString());
        System.out.println(context.getBean(TestService.class));
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        testService.test();
        return "test";
    }

    @RequestMapping(value = "/test/form")
    @ResponseBody
    public String hello(String myname, HttpServletResponse response) {
        System.out.println(myname);
        System.out.println(response.getCharacterEncoding());
        return "hello 中 !" + myname;
    }

    @RequestMapping(value = "/qrTest")
    @ResponseBody
    public String qrTest(String str) {
        return "qrTest";
    }

    @RequestMapping(value = "/webSocketPushMsg/{userId}")
    @ResponseBody
    public String webSocketPushMsg(@PathVariable String userId, String message) {
        Map<RequestMappingInfo, HandlerMethod> map = this.handlerMapping.getHandlerMethods();
        /*Method method = map.get("/qrTest").getMethod();
        Class<?>[] paramTypes = method.getParameterTypes();
        Object[] paramValus = new Object[paramTypes.length];
        method.invoke(map.get("/qrTest"), paramValus);*/
        Iterator<?> iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry entry = (Map.Entry) iterator.next();
            System.out.println(entry.getKey() +"\n" + entry.getValue());
            RequestMappingInfo requestMappingInfo = (RequestMappingInfo)entry.getKey();
            String s = requestMappingInfo.getPatternsCondition().toString();
            if (s.equals("[/qrTest]")){
                System.out.println("equal");
                HandlerMethod handlerMethod= (HandlerMethod)entry.getValue();
                Method method=handlerMethod.getMethod();

                try {
                    method.invoke(handlerMethod.getBeanType(),"123");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        Session session = redisTemplate.opsForValue().get(userId);
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

//    @RequestMapping(value="/test/query")
//    @ResponseBody
//    public String query(int id) {
//        return userMapper.selectByPrimaryKey(id).getUserName();
//    }
}
